<template>
	<div>
		<el-card>
			<el-row>
				<el-col>
					<!-- 添加角色按钮 -->
					<el-button type="primary" @click="dialogVisible=true">添加角色</el-button>
				</el-col>
			</el-row>
			<!-- 角色列表 -->
			<el-table :data="rightList" border stripe>
				<!-- 展开列 -->
				<el-table-column type="expand">
					<template v-slot="scope">
						<el-row :class="['dbbottom', i1 === 0 ? 'dbtop' : '', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
							<!-- 渲染一级权限 -->
							<el-col :span="5">
								<el-tag closable @close="remoId(scope.row, item1.id)">{{item1.authName}}</el-tag>
								<i class="el-icon-caret-right"></i>
							</el-col>

							<!-- 渲染2级，3级权限 -->
							<el-col :span="19">
								<!-- 2级权限 -->
								<el-row :class="[i2 === 0 ? '' : 'dbtop', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
									<el-col :span="6">
										<el-tag type="success" closable @close="remoId(scope.row, item2.id)">{{item2.authName}}</el-tag>
										<i class="el-icon-caret-right"></i>
									</el-col>
									<!-- 三级权限 -->
								  <el-col :span="18">
										<el-tag type="warning" v-for="(item3, i3) in item2.children" :key="item3.id" closable @close="remoId(scope.row, item3.id)">
											{{item3.authName}}</el-tag>
									</el-col>
								</el-row>
							</el-col>
						</el-row>
						<!-- 				<pre>
						{{scope.row}}
					</pre> -->
					</template>
				</el-table-column>
				<!-- 索引列 -->
				<el-table-column type="index"></el-table-column>
				<el-table-column label="角色名称" prop="roleName"></el-table-column>
				<el-table-column label="角色描述" prop="roleDesc"></el-table-column>
				<el-table-column label="操作" width="300px">
					<template v-slot="scope">
						<el-button size="mini" type="primary" icon="el-icon-edit" @click="showXiu(scope.row.id)">编辑</el-button>
						<el-button size="mini" type="danger" icon="el-icon-delete" @click="removeUser(scope
						.row.id)">删除</el-button>
						<el-button size="mini" type="warning" icon="el-icon-setting" @click="jurisdiction(scope.row)">分配权限</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<el-dialog title="提示" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
			<el-form :model="addForm" :rules="addFormrules" ref="addruleForm">
				<el-form-item label="用户名称" prop="username">
					<el-input v-model="addForm.username"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="addForm.password"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input type="email" v-model="addForm.email"></el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="mobile">
					<el-input v-model="addForm.mobile"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 修改用户信息对话框 -->
		<el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editClose">
			<el-form :model="editFrom" :rules="ruleseditRules" ref="editFromRef" label-width="70px">
				<el-form-item label="用户名">
					<el-input v-model="editFrom.username" disabled></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="editFrom.email"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="mobile">
					<el-input v-model="editFrom.mobile"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="editUserInfo">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 分配对话框 -->
		<el-dialog
		  title="分配权限"
		  :visible.sync="fendialogVisible"
		  width="50%" @click="setRights">
		  <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defkeys" ref="treeRef"></el-tree>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="fendialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="allorights">确 定</el-button>
		  </span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		data() {
			var checkEmail = (rule, value, cb) => {
				// console.log(rule, value, cb)
				const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
				if (regEmail.test(value)) {
					return cb()
				}
				cb(new Error('输入正确邮箱'))
			}

			var checkMobile = (rule, value, cb) => {
				const regMobile = /^(1[3|5-9])\d{9}$/
				if (regMobile.test(value)) {
					return cb()
				}
				cb(new Error('输入正确手机号'))
			}
			return {
				rightList: [],
				dialogVisible: false,
				addForm: {
					username: '',
					password: '',
					email: '',
					mobile: ''
				},

				editDialogVisible: false,

				editFrom: {},
				// 分配权限对话框开关
				fendialogVisible: false,
				// 所有权限数据
				rightsList: [],
				// 树形控件属性绑定对象
				treeProps: {
					label: 'authName',
					children: 'children'
				},
				defkeys: [],
				//当前即将分配权限的角色id
				roleId: '',

				addFormrules: {
					username: [{
							required: true,
							message: '请输入用户名',
							trigger: 'blur'
						},
						{
							min: 3,
							mix: 10,
							message: '用户名长度在3~10位',
							trigger: 'blur'
						}
					],
					password: [{
							required: true,
							message: '请输入密码',
							trigger: 'blur'
						},
						{
							min: 3,
							mix: 10,
							message: '用户名长度在3~10位',
							trigger: 'blur'
						}
					],
					email: [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							validator: checkEmail,
							trigger: 'blur'
						}
					],
					mobile: [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							validator: checkMobile,
							trigger: 'blur'
						}
					]
				},
				ruleseditRules: {
					email: [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							validator: checkEmail,
							trigger: 'blur'
						}
					],
					mobile: [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							validator: checkMobile,
							trigger: 'blur'
						}
					]
				}
			}
		},
		created() {
			this.getRigst()

		},
		methods: {
			async getRigst() {
				const {
					data: res
				} = await this.$http.get('/roles')
				if (res.meta.status !== 200) {
					return this.$message.error('获取失败')
				}
				this.rightList = res.data
				console.log(this.rightList)
			},

			addDialogClosed() {
				this.$refs.addruleForm.resetFields()
			},

			async getUsers() {
				this.$refs.addruleForm.validate(async valid => {
					if (!valid) return
					const {
						data: res1
					} = await this.$http.post('/roles111', this.addForm)

					if (res1.meta.status !== 200) {
						return this.$message.error("失败")
					}
					this.$message.success('成功')
					this.dialogVisible = false
					this.getRigst()
				})
			},
			async showXiu(id) {
				const {
					data: res
				} = await this.$http.get('/roles/' + id)
				console.log(res)
				if (res.meta.status !== 200) {
					return this.$message.error('编辑失败')
				}
				this.editFrom = res.data
				this.editDialogVisible = true
			},
			editClose() {
				this.$refs.editFromRef.resetFields()
			},
			editUserInfo() {
				this.$refs.editFromRef.validate(async valid => {
					if (!valid) return
					const {
						data: res2
					} = await this.$http.put('/roles/' + this.editFrom.id, {
						roleName: this.editFrom.roleName,
						roleDesc: this.editFrom.roleDesc
					})
					if (res2.meta.status !== 200) {
						return this.$message.error('失败')
					}
					// 关闭对话框
					this.editDialogVisible = false
					// 刷新数据列表
					this.getRigst()
					// 提示修改成功
					this.$message.success('成功')
				})
			},
			async removeUser(id) {
				console.log(id);
				const res = await this.$confirm('是否删除, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch(err => err)

				// 如果确认删除返回字符串confirm，如果取消返回cancel
				// console.log(res)
				if (res !== 'confirm') {
					return this.$message.info('已取消删除')
				}

				const {
					data: res1
				} = await this.$http.delete('/roles2/' + id)
				if (res1.meta.status !== 200) {
					return this.$message.error('删除失败')
				}
				this.$message.success('删除成功')
				this.getRigst()
				// console.log(this.getRigst())

			},
			// 删除对应权限
			async remoId(role, rigthId) {
				const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch(err => err)
				if(confirmRes !== 'confirm') {
					return this.$message.info('取消删除')
				}
				const {data : res} = await this.$http.delete(`/roles/${role.id}/rights/${rigthId}`)
				if(res.meta.status !== 200) {
					return $message.error('删除失败')
				}
				
				// 刷新数据会使得整个页面渲染
				// this.getRigst()
				role.children = res.data
			},
			//点击分配权限对话框
			async jurisdiction(role) {
				this.roleId = role.id
				const {data:res} = await this.$http.get('/rights123/tree')
				if(res.meta.status !== 200) {
					return $message.error('获取失败')
				}
				
				this.rightsList = res.data
				
				// console.log(this.rightsList)
				
				this.getleafKeys(role, this.defkeys)
				
				this.fendialogVisible = true
			},
			getleafKeys(node, arr) {
				if(!node.children) {
					return arr.push(node.id)
				}
				node.children.forEach(item => 
					this.getleafKeys(item,arr))
			},
			// 监听分派对话框关闭事件
			setRights() {
				this.defkeys = []
			},
			//点击分配角色权限
			async allorights() {
				const keys = [
					...this.$refs.treeRef.getCheckedKeys(),
					...this.$refs.treeRef.getHalfCheckedKeys()
				]
				
				const str = keys.join(',')
				console.log(str)
				const {data: res} = await this.$http.post(`/roles/${this.roleId}/rights`,{rids:str})
				if(res.meta.status !== 200) {
					return $message.error('失败了')
				}
				this.$message.success('成功了')
				this.getRigst()
				this.fendialogVisible = false
			}
		}
	}
</script>

<style lang="less" scoped>
	.el-tag {
		margin: 7px;
	}

	.dbbottom {
		border-bottom: 1px solid #eee;
	}

	.dbtop {
		border-top: 1px solid #eee;
	}

	.vcenter {
		display: flex;
		align-items: center;
	}
</style>
